/*
 * Copyright (c) 2021 hpmicro
 *
 * SPDX-License-Identifier: BSD-3-Clause
 *
 */

#include <stdio.h>
#include "board.h"
#include "hpm_debug_console.h"
#include "hpm_gpio_drv.h"
#include "hpm_ppor_drv.h"
#include "boot_user.h"
#include "ota_api.h"
#include "flash_map.h"
#if USER_OTA_MODE_ENET
#include "lwip.h"
#endif
#if USER_OTA_MODE_UART
#include "uart_xmodem.h"
#endif

#define LED_FLASH_PERIOD_IN_MS 300

extern void msc_ram_init(void);
 /* Write file to flash */
static int writefile(unsigned char* data, int len)
{
    /* First packet contain file header info */
    ota_board_auto_write((void*)data, len);
    return 0;
}


void isr_gpio(void)
{
    gpio_clear_pin_interrupt_flag(BOARD_APP_GPIO_CTRL, BOARD_APP_GPIO_INDEX,
                        BOARD_APP_GPIO_PIN);
    printf("user key pressed\n");
    ppor_sw_reset(HPM_PPOR, 10);
}
SDK_DECLARE_EXT_ISR_M(BOARD_APP_GPIO_IRQ, isr_gpio)

void pbutn_gpio_input_interrupt(void)
{
    gpio_interrupt_trigger_t trigger;

    printf("key init\n");
    gpio_set_pin_input(BOARD_APP_GPIO_CTRL, BOARD_APP_GPIO_INDEX,
                           BOARD_APP_GPIO_PIN);

    trigger = gpio_interrupt_trigger_edge_falling;

    gpio_config_pin_interrupt(BOARD_APP_GPIO_CTRL, BOARD_APP_GPIO_INDEX,
                           BOARD_APP_GPIO_PIN, trigger);
    gpio_enable_pin_interrupt(BOARD_APP_GPIO_CTRL, BOARD_APP_GPIO_INDEX,
                           BOARD_APP_GPIO_PIN);
    intc_m_enable_irq_with_priority(BOARD_APP_GPIO_IRQ, 1);
}

void board_testpin_init(void)
{
    uint32_t pad_ctl = IOC_PAD_PAD_CTL_PE_SET(1) | IOC_PAD_PAD_CTL_PS_SET(1);
    HPM_IOC->PAD[IOC_PAD_PZ08].FUNC_CTL = IOC_PZ08_FUNC_CTL_GPIO_Z_08;
    HPM_IOC->PAD[IOC_PAD_PZ08].PAD_CTL = pad_ctl;
    /* PZ port IO needs to configure BIOC as well */
    HPM_BIOC->PAD[IOC_PAD_PZ08].FUNC_CTL = IOC_PZ08_FUNC_CTL_SOC_PZ_08;
    gpio_set_pin_output_with_initial(HPM_GPIO0, GPIO_DO_GPIOZ, 8, 1);
}

int main(void)
{
    int u, ret;
    board_testpin_init();
    board_init();
    board_init_led_pins();
    board_init_gpio_pins();

    board_timer_create(LED_FLASH_PERIOD_IN_MS, board_led_toggle);
#if BOOTUSER_OTA1
    printf("hello world, THIS OTA1\n");
#endif
#if BOOTUSER_OTA2
    printf("hello world, THIS OTA2\n");
#endif
    pbutn_gpio_input_interrupt();

    ota_board_flash_init();
#if USER_OTA_MODE_ENET
    printf("support enet ota!\n");
    lwip_bootuser();
#endif

#if USER_OTA_MODE_UART
    printf("support uart of xmodel ota!\n");
    ret = xmodemReceive(NULL, 0, writefile);
    if (ret > 0)
        ota_board_complete_reset();
#endif

#if USER_OTA_MODE_USB
    printf("support usb of cherryusb ota!\n");
    board_init_usb_pins();

    msc_ram_init();
#endif

    while (1)
    {
        
    }
    return 0;
}
